package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class RefreshInterceptor implements HandlerInterceptor {
    private StringRedisTemplate redisTemplate;
    public RefreshInterceptor(StringRedisTemplate redisTemplate) {
        this.redisTemplate =redisTemplate;
    }
// 该拦截器是在用户浏览的过程中对Redis有效期进行刷新
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//       在登录之前进行拦截 从Redis中获取对象
        String token = request.getHeader("authorization");

        if (token==null){
            return true;
        }
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(RedisConstants.LOGIN_USER_KEY + token);
        if (entries.isEmpty()) {
//            说明用户已经被Redis销毁
            return true;
        }
        UserDTO userDTO = BeanUtil.fillBeanWithMap(entries, new UserDTO(), false);
//          获取到了user信息 添加到ThreadLocal中
        UserHolder.saveUser(userDTO);
//        刷新有效期
        redisTemplate.expire(RedisConstants.LOGIN_USER_KEY + token, RedisConstants.LOGIN_USER_TTL, TimeUnit.SECONDS);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        从ThreadLocal中移除 防止内存泄露问题
        UserHolder.removeUser();
//        从redis中删除对应的token
    }
}
